package com.xuef.controller;

import com.xuef.base.ApiResponse;
import com.xuef.base.Cons;
import com.xuef.entity.Blog;
import com.xuef.entity.User;
import com.xuef.service.BlogService;
import com.xuef.service.ILikeService;
import com.xuef.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by moveb on 2018/5/21.
 */
@Controller
public class LikeController {
    @Autowired
    private IUserService userService;
    @Autowired
    private BlogService blogService;
    @Autowired
    private ILikeService likeService;

    @PostMapping("/blog/like")
    @ResponseBody
    public ApiResponse like(@RequestParam("blogId") Integer blogId,
                            Authentication authentication){
        User user = null;
        int likeCount = 0;
        if(authentication != null && authentication.isAuthenticated()){
            user = userService.findByUsername(authentication.getName());
            likeCount = likeService.like(user.getId(), Cons.ENTITY_TYPE.ENTITY_BLOG, blogId);
            // 更新数据库的 likeCount
            Blog blog = blogService.getBlogById(blogId);
            if(blog != null){
                blog.setLikeCount(likeCount);
                blogService.saveBlog(blog);
            }
            return ApiResponse.ofSuccess(likeCount);
        }else{
            // 用户没有登录
            return ApiResponse.ofMessage(403, "未登录");
        }
    }

    @PostMapping("/blog/dislike")
    @ResponseBody
    public ApiResponse dislike(@RequestParam("blogId") Integer blogId,
                            Authentication authentication){
        User user = null;
        int likeCount = 0;
        if(authentication != null && authentication.isAuthenticated()){
            user = userService.findByUsername(authentication.getName());
            likeCount = likeService.dislike(user.getId(), Cons.ENTITY_TYPE.ENTITY_BLOG, blogId);
            // 更新数据库的 likeCount
            Blog blog = blogService.getBlogById(blogId);
            if(blog != null){
                blog.setLikeCount(likeCount);
                blogService.saveBlog(blog);
            }
            return ApiResponse.ofSuccess(likeCount);
        }else{
            return ApiResponse.ofMessage(403, "未登录");
        }
    }
}
